package com.google.ma.rssreader;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class RssDAO {

    private static final String DB_NAME = "rssreader.db";

    SQLiteDatabase db;

    Context context;

    RssDAO(Context context) {
        this.context = context;
        db = context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
        db.execSQL("create table if not exists rsslist (_id integer primary key autoincrement, title text, url text);");
        Cursor counter = db.query("rsslist", new String[] { "count(_id)" }, null, null, null, null, null);
        counter.moveToFirst();
        int count = counter.getInt(0);
        if (count == 0) {
            db.execSQL("insert into rsslist (title, url) values('CnBeta', 'http://www.cnbeta.com/backend.php');");
        }
    }

    public ArrayList<HashMap<String, String>> queryList(String title) {
        Cursor cur;
        if (title == null) {
            cur = db.query("rsslist", new String[] { "title", "url" }, null, null, null, null, null);
        } else {
            cur = db.query("rsslist", new String[] { "title", "url" }, "title=?", new String[] { title }, null, null, null);
        }
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        cur.moveToFirst();
        while (!cur.isAfterLast()) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("title", cur.getString(0));
            map.put("url", cur.getString(1));
            list.add(map);
            cur.moveToNext();
        }

        return list;
    }

    public boolean insert(String title, String url) {
        try {
            db.execSQL("insert into rsslist (title, url) values (?, ?);", new String[] { title, url });
        } catch (SQLException e) {
            return false;
        }
        return true;
    }
    
    public boolean delete(String title) {
        try {
            db.execSQL("delete from rsslist where title=?;", new String[] { title });
        } catch (SQLException e) {
            return false;
        }
        return true;
    }
}
